import { defineMock } from "../base";

// 局部变量存储稳控切负荷信息
let sheddingData = {
  shedding_name: "切负荷层级",
  shedding_value: 1,
  shedding_min: 0,
  shedding_max: 5,
  shedding_enable: true,
  recover_name: "恢复负荷层级",
  recover_value: 3,
  recover_min: 0,
  recover_max: 6,
  recover_enable: true,
};

export default defineMock([
  // GET uri: /api/shedding/{cpu} 查询稳控切负荷信息
  {
    url: "shedding/:cpu",
    method: ["GET"],
    body({ query, params }) {
      console.log("[MOCK] GET shedding/:cpu", query, params);
      return { ...sheddingData };
    },
  },

  // POST uri: /api/shedding/{cpu}/{type} 修改切负荷层级
  {
    url: "shedding/:cpu/:type",
    method: ["POST"],
    body({ query, params, body }) {
      console.log("[MOCK] POST shedding/:cpu/:type", query, params, body);
      
      const cpu = parseInt(params.cpu);
      const type = parseInt(params.type);
      const { value } = body;

      // 验证参数
      if (type === 0) {
        // 切负荷层级
        if (value < sheddingData.shedding_min || value > sheddingData.shedding_max) {
          return {
            cpu,
            type,
            status: false,
            error: `切负荷层级值必须在 ${sheddingData.shedding_min}-${sheddingData.shedding_max} 范围内`,
          };
        }
        if (!sheddingData.shedding_enable) {
          return {
            cpu,
            type,
            status: false,
            error: "切负荷层级功能未启用",
          };
        }
        // 更新切负荷层级值
        sheddingData.shedding_value = value;
      } else if (type === 1) {
        // 恢复负荷层级
        if (value < sheddingData.recover_min || value > sheddingData.recover_max) {
          return {
            cpu,
            type,
            status: false,
            error: `恢复负荷层级值必须在 ${sheddingData.recover_min}-${sheddingData.recover_max} 范围内`,
          };
        }
        if (!sheddingData.recover_enable) {
          return {
            cpu,
            type,
            status: false,
            error: "恢复负荷层级功能未启用",
          };
        }
        // 更新恢复负荷层级值
        sheddingData.recover_value = value;
      } else {
        return {
          cpu,
          type,
          status: false,
          error: "无效的类型参数，type 必须为 0 或 1",
        };
      }

      return {
        cpu,
        type,
        status: true,
      };
    },
  },
]);
